const express = require('express')
const userRouter = express.Router()
const createError = require('http-errors')
const fs = require('fs')


userRouter.route('/login')
    .post((req, res, next) => {
        const user = req.body
        // 查看是否有用户
        fs.readFile('./router/user.json', 'utf-8', (err, data) => {
            if (err) next(createError('no file'))
            else {
                const users = JSON.parse(data)
                const DbUser = users.filter(v => v.name === user.name)
                console.log(DbUser)
                if (DbUser.length === 0) next(createError(403, 'no user'))
                else if (DbUser[0].pwd !== user.pwd) next(createError(403, 'wrong password'))
                else {
                    req.session.status = 'login success'
                    res.end('login success!')
                }
            }
        })
    })
    .get((req, res, next) => {
        if (req.session.status) {
            res.redirect('/')
        } else res.end('welcome to login')

    })

userRouter.route('/signup')
    .post((req, res, next) => {
        const user = req.body
        // 查看是否有同名用户
        // 有的话返回错误
        // 如果没有就可以注册
        fs.readFile('./router/user.json', 'utf-8', (err, data) => {
            if (err) next(createError('no file'))
            else {
                const users = JSON.parse(data)
                const DbUser = users.filter(v => v.name === user.name)
                if (DbUser.length !== 0) next(createError(403, '已存在用户'))
                else {
                    users.push(user)
                    fs.writeFile('./router/user.json', JSON.stringify(users), (err, result)=> {
                        if (err) next(createError('注册失败！'))
                        else res.end('注册成功！')
                    }) 
                }
            }
        })
    })
    .get((req, res) => {
        if (req.session.status) {
            res.redirect('/')
        } else res.end('welcome to signup')

    })
userRouter.route('/logout')
    .get((req, res) => {
        req.session.status = null
        res.redirect('/')
    })
module.exports = userRouter

